package clock;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.JPanel;

import clock.hand.ClockHand;
import clock.hand.HourHand;
import clock.hand.MinuteHand;
import clock.hand.SecondHand;

public class ClockCanvas extends JPanel {

	private static final long serialVersionUID = 1L;
	private final ClockHand hourHand, minuteHand, secondHand;
	private BufferedImage divisionsImg;
	
	private final int axisX, axisY;
	
	public ClockCanvas(int width, int height, int axisX, int axisY) {
		this.axisX = axisX;
		this.axisY = axisY;
		secondHand = new SecondHand(axisX, axisY);
		minuteHand = new MinuteHand(axisX, axisY);
		hourHand = new HourHand(axisX, axisY);
		super.setSize(width, height);
		this.init();
	}
	
	@Override
	public void paintComponent(Graphics g) {
		g.clearRect(0, 0, this.getWidth(), this.getHeight());
		g.drawImage(this.divisionsImg, 0, 0, null);
		Graphics2D g2d = (Graphics2D)g;
		this.secondHand.draw(g2d);
		this.hourHand.draw(g2d);
		this.minuteHand.draw(g2d);
		
		g.setColor(Color.black);
		SimpleDateFormat sdf = new SimpleDateFormat("hh시 mm분 ss초", Locale.KOREA);
		String strTime = sdf.format(new Date());
		int strWidth = g.getFontMetrics().stringWidth(strTime);
		g.drawString(strTime, (Clock.WIDTH-strWidth)/2, Clock.HEIGHT - 60);
		g.fillOval(this.axisX-4, this.axisY-4, 7, 7);
		g.setColor(Color.white);
		g.fillOval(this.axisX-2, this.axisY-2, 4, 4);
	}
	
	private void init() {
		divisionsImg = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
		
		Graphics2D g = divisionsImg.createGraphics();
		
		g.setColor(Color.black);
		Ellipse2D.Double ellipse = new Ellipse2D.Double(0, 0, 7.f, 7.f);
		for(int i = 1; i <= 60; i++) {
			int x = 0;
			int y = 0;
			x = (int) (80 * Math.cos(Math.toRadians(i*6)) + this.axisX);
			y = (int) (80 * Math.sin(Math.toRadians(i*6)) + this.axisY);
			g.drawOval(x-1, y-1, 2, 2);
			if (i % 5 == 0) {
				ellipse.x = x-4;
				ellipse.y = y-4;
				g.fill(ellipse);
			}
		}
		g.dispose();
	}
}
